<!-- 折叠面板 -->
<template>
    <div class="collapse">
        <div style="overflow: hidden">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" style="float: left">全选</el-checkbox>
            <!-- <el-button type="text" class="button" @click="withdraw" style="color: #409eff">撤回</el-button> -->
        </div>

        <el-collapse class="margin-top" v-model="activeNames" @change="handleChange" v-if="CollapseData && CollapseData.length>0">
            <el-collapse-item :name="i.id" v-for="i in CollapseData" :key="i.id">
                <template slot="title">
                    <div @click="stopProp">
                        <el-checkbox
                            :indeterminate="i.indeterminate"
                            v-model="i.selected"
                            @change="(checked) => collapseItemChange(checked, i.data, i.id)"
                        >
                            <span v-if="i.snId && pathUrl == '/Borrow'"> {{ i.snId + " - " }}</span>
                            <span :title="i.name + '(' + i.data.length + ' )'">{{ i.name + "(" + i.data.length + ")" }}</span>
                        </el-checkbox>
                    </div>
                </template>
                <div>
                    <div style="margin: 15px 0"></div>

                    <el-checkbox
                        ref="treeCheckBox"
                        v-for="(s, indexData) in i.data"
                        v-model="s.selected"
                        @change="threeLevelChange(i.name, indexData)"
                        :key="indexData + 'data'"
                        :label="s.id"
                    >
                        <div style="width: 100%">
                            <span v-if="s.fileCategory">{{ s.fileCategory }} : </span>

                            <span v-if="s.fileId">{{ s.fileId | getFileNo }} - </span>
                            <span v-if="s.id && pathUrl == '/FileInfoDetails'">{{ s.id | getFileNo }} - </span>
                            <!-- <span v-if="s.fileNo">{{ s.fileNo }} - </span> -->
                            <span :title="s.name" class="collapse-name">{{ s.name }}</span>
                        </div>
                    </el-checkbox>
                </div>
            </el-collapse-item>
        </el-collapse>

        <div v-else class="nodata">
            暂无数据
        </div>
    </div>
</template>

<script>
export default {
    name: "",
    data() {
        return {
            CollapseData: [], //渲染数据
            activeNames: [],
            checkedCities: [], //选中值
            checkAll: false, // 全选/取消全选 状态
            isIndeterminate: false, // 半选中
            cities: [],
            pathUrl: "",
            isClickChecked: false,
            tabsPaneName: "saveSelectedData" + this.tabsPane,
        }
    },
    props: {
        zCollapseData: Array,
        tabsPane: String,
    },
    components: {},
    filters: {
        getFileNo(val) {
        
            let data = val.split("_")

            if(!data[2]) return data[1]
            return data[1] + "_" + data[2]
        },
    },
    computed: {},
    watch: {
        zCollapseData(val) {
            this.$nextTick((e) => {
                const router = this.$route.path
                this.CollapseData = val
                this.isClickChecked = true
                sessionStorage.setItem(this.tabsPaneName, JSON.stringify([]))
                this.threeLevelChange()
            })
        },
        CollapseData: {
            handler: function (val, oldVal) {
                /****************** 撤销 ********************/
                // let data1 = JSON.parse(sessionStorage.getItem(this.tabsPaneName))
                // this.CollapseData.length > 0 && data1.push(this.CollapseData)
                // console.log("🚀 ~ file: index.vue:172 ~ threeLevelChange ~ data1", data1)
                // sessionStorage.setItem(this.tabsPaneName, JSON.stringify(data1))
            },
            immediate: true,
            deep: true,
        },
    },
    mounted() {
        this.getPathUrl()
    },
    wahch: {},
    methods: {
        //初始化数据
        initData() {
            let preindex = 0

            this.CollapseData = this.zCollapseData.reduce((pre, item, index) => {
                let data = {
                    data: [],
                    id: item.id,
                    snId: item.snId,
                    name: item.title,
                    uploadTime: item.uploadTime,
                    userId: item.userId,
                    indeterminate: false,
                    selected: false,
                }
                let fileData = { fileId: item.fileId, name: item.fileName, selected: false }
                if (pre.length == 0) {
                    pre.push(data)
                    pre[preindex].data.push(fileData)
                    return pre
                }
                if (pre.some((e) => e.title == item.title)) {
                    pre[preindex].data.push(fileData)
                } else {
                    pre.push(data)
                    preindex++
                    pre[preindex].data.push(fileData)
                }
                return pre
            }, [])
        },
        handleChange(val) {
            this.cities = []
            val.forEach((e) => {
                this.zCollapseData.filter((s) => {
                    if (s.name == e) this.cities.push(s.data)
                })
            })
        },
        //全部  全选/取消全选
        handleCheckAllChange(val) {
            this.checkedCities = val ? this.getSelectAllData(this.CollapseData) : []
            this.isIndeterminate = false

            this.CollapseData.map((e) => {
                e.selected = val //二级菜单 全选/取消全选
                e.data.map((s) => (s.selected = val)) //三级菜单 全选/取消全选
            })
            this.threeLevelChange()
        },

        //获取全选数组
        getSelectAllData(SelectData) {
            let data = []
            SelectData.map((s) => s.data.map((e) => data.push(e.id)))
            return data
        },
        //二级
        collapseItemChange(val, data, id) {
            val && id && this.activeNames.push(id)
            data.map((e) => (e.selected = val)) //三级全选/取消全选
            this.threeLevelChange()
        },
        //三级
        threeLevelChange(name, index, id) {
            let topALL = []

            this.CollapseData.map((e) => {
                let threeAll = [...e.data].every((s) => s.selected)
                let threeOne = [...e.data].some((s) => s.selected)
                threeAll && (e.selected = threeAll) //二级全选
                if (!threeAll & !threeOne) e.selected = false ////二级取消全选
                e.indeterminate = !threeAll & threeOne ? true : false //二级 半选状态

                e.data.map((g) => topALL.push(g.selected)) //用于一级全选判断
            })
            let firstAll = [...topALL].every((s) => s)
            let firstOne = [...topALL].some((s) => s)
            firstAll && (this.checkAll = firstAll) //一级全选
            if (!firstAll & !firstOne) this.checkAll = false ////一级取消全选
            this.isIndeterminate = !firstAll & firstOne ? true : false //一级 半选状态
        },
        //阻止冒泡事件
        stopProp(e) {
            e.stopPropagation()
        },

        //获取总数据条数
        getTotal() {
            return this.zCollapseData.reduce((e, s) => {
                return e + s.data.length
            }, 0)
        },
        //递归遍历全部数据 按钮状态改变 遍历全部数据
        recursionCollapseData(CollapseData, firstdata) {
            this.flatToTree(JSON.parse(JSON.stringify(this.CollapseData)), this.zCollapseData)
        },
        flatToTree(flatList, treeList) {
            flatList.map((e) => {
                // 以 e.pid===null,作为判断是不是根节点的依据，或者直接写死根节点（如果确定的话），
                // 具体以什么作为判断根节点的依据，得看数据的设计规则，通常是判断层级或是否代表根节点的标记
                if (e.pid === null) {
                    // 避免出现重复数据
                    const index = treeList.findIndex((sub) => sub.id === e.id)
                    if (index === -1) {
                        treeList.push(e)
                    }
                }

                flatList.map((e2) => {
                    if (e2.pid === e.id) {
                        // 避免出现重复数据
                        const index = e.data.findIndex((sub) => sub.id === e2.id)
                        if (index === -1) {
                            e.children.push(e2)
                        }
                    }
                })
            })

            return treeList
        },
        //获取选中文件 删除 扁平化
        getDelSelectData() {
            let edata = []
            this.CollapseData.map((e) => {
                if (e.indeterminate || e.selected) {
                    e.data.map((s) => {
                        let sdata = {}
                        if (s.selected === true) {
                            // sdata.snId = e.id
                            // sdata.title = e.name
                            // sdata.fileId = s.id
                            // sdata.fileName = s.name
                            edata.push(s.id)
                        }
                    })
                }
            })
            return edata
        },
        //获取选中文件 上传 扁平化
        getSelectData() {
            let edata = []
            this.CollapseData.map((e) => {
                if (e.indeterminate || e.selected) {
                    e.data.map((s) => {
                        let sdata = {}
                        if (s.selected === true) {
                            sdata.id = s.id
                            sdata.userId = e.userId
                            sdata.snId = e.snId
                            sdata.title = e.name
                            sdata.fileId = s.fileId
                            sdata.fileName = s.name
                            sdata.uploadTime = e.uploadTime
                            edata.push(sdata)
                        }
                    })
                }
            })
            return edata
        },
        //判断是否选中数据 返回选中文件
        setCheckData() {
            if (this.checkAll || this.isIndeterminate) {
                return this.getDelSelectData()
            } else {
                this.$message.error("请选择数据!")
                return false
            }
        },
        //撤回
        withdraw() {
            let data = JSON.parse(sessionStorage.getItem(this.tabsPaneName))

            let withdrawData = null
            if (this.isClickChecked) {
                this.isClickChecked = false
                console.log("删除两次")
                let isdata = data.pop()

                withdrawData = data.pop()

                if (withdrawData && withdrawData.length > 0) {
                    this.CollapseData = withdrawData
                }
            } else {
                console.log("删除一次")
                withdrawData = data.pop()
                if (withdrawData && withdrawData.length > 0) {
                    this.CollapseData = withdrawData
                }
            }

            sessionStorage.setItem(this.tabsPaneName, JSON.stringify(data))
        },
        getPathUrl() {
            this.pathUrl = this.$route.path
        },
    },
}
</script>
<style lang='scss' scoped>
.collapse {
    padding: 10px 20px;
    font-size: 28px;

    .el-checkbox {
        width: 100%;
        padding: 5px 0;
    }

    .el-collapse {
        border-top: 0.013333rem solid #ccc;
        border-bottom: none;

        .el-collapse-item {
            // padding: 0 10px;
            margin: 10px 0;
            overflow: hidden;
        }

        ::v-deep .el-collapse-item__header {
            .el-checkbox {
                // color: #02409c;
            }

            font-size: 20px;
            font-weight: 600;
            padding: 0 10px;
        }

        ::v-deep .el-collapse-item__wrap {
            padding: 0 20px;
        }

        ::v-deep .el-checkbox__label {
            font-size: 17px;
            font-weight: 550;
        }
    }

    .el-checkbox__label {
    }

    .el-button {
        position: absolute;
        left: 1.3rem;
        top: 0.01rem;
    }

    .collapse-name {
        // width: 80%;
        // display: block;
        // max-width: 10em; //限制字数
        // overflow: hidden; //对溢出内容的隐藏
        // white-space: nowrap; //只保留一个空白，文本不会换行，会在在同一行上继续，直到遇到br标签为止。
        // text-overflow: ellipsis//使得超出部分用“ … ”代替;
    }
}

.nodata{
    text-align: center;
    line-height:250px;
    color: #838383;

}
</style>